<template>
  <div v-if="globalStore.language" class="login-container">
    <img :src="LoginImage" alt="login" />
    <div class="login-links">
      <div class="login-links-item">
        <a href="https://www.neo-agriservis.ru" target="_blank" />
      </div>
      <div class="login-links-item">
        <a href="https://www.qifasilu.com" target="_blank" />
      </div>
      <div class="login-links-item">
        <a href="https://www.hyscm.com" target="_blank" />
      </div>
      <div class="login-links-item">
        <a href="https://www.onemig369.com" target="_blank" />
      </div>
      <div class="login-links-item">
        <a href="http://www.hygfm.com" target="_blank" />
      </div>
    </div>
    <div class="login-header">
      <img :src="loginText" alt="merak" width="138" />
      <el-dropdown popper-class="login-popper" @command="handleCommand">
        <div class="login-language">
          <el-icon size="18">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
              <path
                d="M16.36,14C16.44,13.34 16.5,12.68 16.5,12C16.5,11.32 16.44,10.66 16.36,10H19.74C19.9,10.64 20,11.31 20,12C20,12.69 19.9,13.36 19.74,14M14.59,19.56C15.19,18.45 15.65,17.25 15.97,16H18.92C17.96,17.65 16.43,18.93 14.59,19.56M14.34,14H9.66C9.56,13.34 9.5,12.68 9.5,12C9.5,11.32 9.56,10.65 9.66,10H14.34C14.43,10.65 14.5,11.32 14.5,12C14.5,12.68 14.43,13.34 14.34,14M12,19.96C11.17,18.76 10.5,17.43 10.09,16H13.91C13.5,17.43 12.83,18.76 12,19.96M8,8H5.08C6.03,6.34 7.57,5.06 9.4,4.44C8.8,5.55 8.35,6.75 8,8M5.08,16H8C8.35,17.25 8.8,18.45 9.4,19.56C7.57,18.93 6.03,17.65 5.08,16M4.26,14C4.1,13.36 4,12.69 4,12C4,11.31 4.1,10.64 4.26,10H7.64C7.56,10.66 7.5,11.32 7.5,12C7.5,12.68 7.56,13.34 7.64,14M12,4.03C12.83,5.23 13.5,6.57 13.91,8H10.09C10.5,6.57 11.17,5.23 12,4.03M18.92,8H15.97C15.65,6.75 15.19,5.55 14.59,4.44C16.43,5.07 17.96,6.34 18.92,8M12,2C6.47,2 2,6.5 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z"
              />
            </svg>
          </el-icon>
          <span>{{ languageMap[globalStore.language] }}</span>
          <el-icon>
            <ArrowUp />
          </el-icon>
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="ru">{{ languageMap.ru }}</el-dropdown-item>
            <el-dropdown-item command="zh">{{ languageMap.zh }}</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <div class="login-content">
      <div class="login-content-wrapper">
        <div v-if="account" class="login-avatar">
          <el-avatar
            :size="120"
            :src="globalStore.useravatar ?? 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"
          />
          <span>{{ globalStore.username }}</span>
        </div>
        <h3 v-else>
          {{ $t("newLogin.welcome") }}<span>{{ $t("newLogin.merak") }}</span>
        </h3>
        <el-form ref="formRef" :model="formValue" @submit.native.prevent>
          <el-form-item v-if="!account" prop="username" :rules="[{ required: true, message: $t('newLogin.username') }]">
            <el-input
              v-model.trim="formValue.username"
              autocomplete="new-password"
              :placeholder="$t('newLogin.username')"
              :prefix-icon="User"
            />
          </el-form-item>
          <el-form-item prop="password" :rules="[{ required: true, message: $t('newLogin.password') }]">
            <el-input
              v-model.trim="formValue.password"
              type="password"
              autocomplete="new-password"
              show-password
              :placeholder="$t('newLogin.password')"
              :prefix-icon="Lock"
            />
          </el-form-item>
          <el-form-item v-if="account">
            <el-button link :icon="ArrowRight" @click="account = false">{{ $t("newLogin.other") }}</el-button>
          </el-form-item>
        </el-form>
        <el-button ref="buttonRef" type="primary" :loading="loading" @click="handleLogin">{{ $t("newLogin.button") }}</el-button>
        <a href="https://beian.miit.gov.cn/" target="_blank">
          <el-button type="primary" link>{{ $t("merak.icp") }}</el-button>
        </a>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted, onBeforeUnmount } from "vue";

import { useRouter } from "vue-router";

import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { useUserStore } from "@/stores/modules/user";
import { useGlobalStore } from "@/stores/modules/global";

import {
  ElDropdown,
  ElDropdownMenu,
  ElDropdownItem,
  ElIcon,
  ElAvatar,
  ElForm,
  ElFormItem,
  ElInput,
  ElButton,
  ElMessage
} from "element-plus";
import { ArrowUp, ArrowRight, User, Lock } from "@element-plus/icons-vue";

import LoginImage from "@/assets/images/merak_login_pic_bg@2x.webp";
import loginText from "@/assets/images/logopic_merak@2x.webp";

import { ResultEnum } from "@/enums/httpEnum";
import { loginApi } from "@/api/modules/login";

import { initDynamicRouter } from "@/routers/modules/dynamicRouter";

import { getAlltree } from "@/minxins/useOrgsStore"; //获取组织架构树

import { HOME_URL } from "@/config";

const languageMap = {
  ru: "Русский",
  zh: "简体中文"
};

const router = useRouter();

const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();
const userStore = useUserStore();
const globalStore = useGlobalStore();

const formRef = ref<InstanceType<typeof ElForm>>();

const buttonRef = ref<InstanceType<typeof ElButton>>();

const loading = ref(false);

const account = ref(!!globalStore.useraccount);

const formValue = reactive<{
  username?: string;
  password?: string;
}>({});

const handleCommand = (command: "ru" | "zh") => {
  globalStore.setGlobalState("language", command);
  location.href = location.href;
};

const handleLogin = () => {
  formRef.value?.validate().then(async () => {
    loading.value = true;
    const params = { username: account.value ? globalStore.useraccount : formValue.username, password: formValue.password };

    const diffObj = (obj1: Record<string, any>, obj2: Record<string, any>) => {
      return Object.keys(obj1)
        .concat(Object.keys(obj2))
        .filter(key => obj1[key] !== obj2[key]);
    };

    // @ts-ignore
    await loginApi(params)
      .then(async ({ code, data, message }) => {
        if (code === ResultEnum.SUCCESS) {
          // 记录本地
          if (!account.value) {
            globalStore.setGlobalState("useraccount", formValue.username!);
            globalStore.setGlobalState("username", data.username);
            globalStore.setGlobalState("useravatar", data.head_portrait);
          }

          // 还原用户设置
          if (data?.merak_custom_settings?.userSetMsg) {
            const differences = diffObj(globalStore.$state, data.merak_custom_settings.userSetMsg);
            if (differences.length > 0) {
              globalStore.$state = data?.merak_custom_settings?.userSetMsg;
              const Safari = /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent);
              if (!Safari) {
                location.href = location.href;
              }
            }
          }
          if (data?.merak_custom_settings.tabsMenuList) {
            tabsStore.setTabs(data.merak_custom_settings.tabsMenuList);
          } else {
            tabsStore.setTabs([]);
            keepAliveStore.setKeepAliveName([]);
          }

          // 记录用户信息
          userStore.setUser(data);

          // 添加动态路由
          await initDynamicRouter();

          // 获取初始化组织架构tree
          await getAlltree(); //初始化组织架构

          // 跳转到首页
          router.push(HOME_URL);
        } else {
          const msg = typeof message === "string" ? message : Object.values(message)?.[0];
          ElMessage.error(msg);
        }
      })
      .catch(() => (loading.value = false));
    loading.value = false;
  });
};

const handleKeydown = (event: KeyboardEvent) => {
  if (loading.value) return;
  if (event.code === "Enter" || event.code === "enter" || event.code === "NumpadEnter") {
    handleLogin();
  }
};

watch(
  () => account.value,
  () => {
    if (account.value === false) {
      formRef.value?.resetFields();
    }
  }
);

onMounted(() => {
  document.addEventListener("keydown", handleKeydown);
});

onBeforeUnmount(() => {
  document.removeEventListener("keydown", handleKeydown);
});
</script>

<style scoped lang="scss">
.login-container {
  display: flex;
  height: 100%;
  color: var(--merak-text-color);
  & > img {
    flex-shrink: 0;
    width: 62.5%;
  }
  .login-links {
    position: fixed;
    width: 62.5%;
    height: 100%;
    &-item {
      position: absolute;
      top: 50%;
      left: 50%;
      width: 12%;
      &:nth-child(1) {
        transform: translate(-264%, -125%) scaleY(0.5);
      }
      &:nth-child(2) {
        transform: translate(112%, -125%) scaleY(0.5);
      }
      &:nth-child(3) {
        width: 32%;
        transform: translate(-60%, -37%) scaleY(0.5);
      }
      &:nth-child(4) {
        transform: translate(-264%, 94%) scaleY(0.5);
      }
      &:nth-child(5) {
        transform: translate(112%, 94%) scaleY(0.5);
      }
      a {
        display: block;
        padding-top: 100%;
        width: 100%;
        transform: rotateZ(45deg);
      }
    }
  }
  .login-header {
    position: fixed;
    top: 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 64px;
    width: 100%;
    height: 64px;
    box-sizing: border-box;
  }
  .login-language {
    display: flex;
    align-items: center;
    line-height: 0;
    color: var(--merak-text-color);
    outline: none;
    transition: color 0.5s;
    cursor: pointer;
    &[aria-expanded="true"] {
      color: #0062c4;
      & > .el-icon:last-child {
        transform: rotate(180deg);
      }
    }
    & > span {
      margin: 0 5px;
    }
    & > .el-icon:last-child {
      transition: transform 0.5s;
    }
  }
  .login-content {
    display: flex;
    flex: auto;
    align-items: center;
    justify-content: center;
    &-wrapper {
      width: 400px;
      h3 {
        margin: 0;
        line-height: 44px;
        font-size: 48px;
        font-weight: bold;
        letter-spacing: 0.05em;
        white-space: nowrap;
        span {
          color: #fcae2e;
        }
      }
      .login-avatar {
        display: flex;
        flex-direction: column;
        align-items: center;
        span {
          margin-top: 10px;
          color: #032a50;
          font-size: 24px;
        }
      }
      .el-form {
        margin-top: 80px;
        .el-form-item {
          margin-bottom: 40px;
          &.is-error {
            --el-color-danger: #ff461c;
          }
          .el-input {
            font-size: 16px;
            height: 56px;
            :deep(.el-icon) {
              font-size: 24px;
            }
          }
          .el-button {
            padding: 0;
            flex-direction: row-reverse;
            color: #0062c4;
            font-size: 16px;
            border: none;
            :deep(span) {
              margin-left: 0;
            }
          }
        }
      }
      & > .el-button {
        margin-top: 24px;
        width: 100%;
        height: 56px;
        font-size: 18px;
        background-color: #063f77 !important;
        border-color: transparent !important;
      }
      & > a {
        display: block;
        margin-top: var(--merak-space);
        & > .el-button {
          color: #0062c4 !important;
        }
      }
    }
  }
}
</style>

<style lang="scss">
.login-container {
  min-width: 1024px;
  min-height: 648px;
  input {
    &:-webkit-autofill {
      -webkit-box-shadow: 0 0 0px 1000px #fff inset;
    }
  }
}

.login-popper {
  .el-dropdown-menu__item {
    color: #0062c4 !important;
    &:hover {
      color: #032a50 !important;
      background-color: rgba(0, 98, 196, 0.08) !important;
    }
  }
  .el-popper__arrow {
    display: none;
  }
}
</style>
